package com.ajhlp.android.savecode;

import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import com.ajhlp.android.savecode.db.ConfigOpenHelper;
import com.ajhlp.android.savecode.model.ConfigModel;
import com.ajhlp.android.savecode.util.DateTimeUtil;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MenuItem.OnMenuItemClickListener;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class ConfigManagerActivity extends Activity {
	private ConfigOpenHelper configOpenHelper = new ConfigOpenHelper(this);
	private ConfigListAdapter adapter;
	private AlertDialog addConfigDialog;
	private AlertDialog delConfirmDialog;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_configmanager);
		
		ListView listView = (ListView) findViewById(R.id.listview_config_all);
		adapter = new ConfigListAdapter(this, configOpenHelper.searchAllConfig());
		
		listView.setAdapter(adapter);
		
		listView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> adapterView, View view, int position,
					long rowid) {
				// TODO Auto-generated method stub
				if(adapter.isShowCheckBox() == false){
					return;
				}
				if(adapter.getSelectedConfigs().contains(position)){
					adapter.getSelectedConfigs().remove(position);
				}else{
					adapter.getSelectedConfigs().add(position);
				}
				adapter.notifyDataSetChanged();
			}
		});
		
		if(adapter.getConfigs().size() > 0){
			findViewById(android.R.id.empty).setVisibility(View.INVISIBLE);
		}
		
	}
	
	
	
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		if(adapter == null){
			return;
		}
		if(adapter.getConfigs().size() > 0){
			findViewById(android.R.id.empty).setVisibility(View.INVISIBLE);
		}else{
			findViewById(android.R.id.empty).setVisibility(View.VISIBLE);
		}
	}



	public final void refreshConfigList(){
		adapter.getConfigs().clear();
		adapter.getConfigs().addAll(configOpenHelper.searchAllConfig());
		adapter.setShowCheckBox(false);
		adapter.getSelectedConfigs().clear();
		adapter.notifyDataSetChanged();
	}
	
	public void onNewConfigButtonClick(View view){
		createAddConfigDialog(ConfigManagerActivity.this).show();
	}
	
	public AlertDialog createAddConfigDialog(final Context context){
		if(addConfigDialog == null){
			AlertDialog.Builder builder = new AlertDialog.Builder(context);
			builder.setIcon(android.R.drawable.ic_dialog_info);
			builder.setTitle(R.string.dialog_title_config_manage_new);
			LayoutInflater inflater = LayoutInflater.from(context);
			builder.setView(inflater.inflate(R.layout.dialog_config_manage_new, null));
			builder.setPositiveButton(R.string.text_button_save, new DialogInterface.OnClickListener() {
				
				public void onClick(DialogInterface dialog, int buttonid) {
					// TODO Auto-generated method stub
					AlertDialog d = (AlertDialog)dialog;
					EditText numberField = (EditText) d.findViewById(R.id.config_manage_new_number);
					EditText contentField = (EditText) d.findViewById(R.id.config_manage_new_content);
					EditText countField = (EditText) d.findViewById(R.id.config_manage_new_count);
					EditText nameField = (EditText) d.findViewById(R.id.config_manage_new_name);
					
					if(numberField.getText().toString().trim().equals("")){
						return;
					}
					if(contentField.getText().toString().trim().equals("")){
						return;
					}
					if(countField.getText().toString().trim().equals("")){
						return;
					}
					if(nameField.getText().toString().trim().equals("")){
						return;
					}
					
					ConfigModel configModel = new ConfigModel(nameField.getText().toString(), numberField.getText().toString(), contentField.getText().toString(), Integer.parseInt(countField.getText().toString()));
					configModel.setLast_edit(System.currentTimeMillis());
					
					try {
						configOpenHelper.saveConfig(configModel);
						Toast.makeText(context, R.string.text_config_manage_result_success, Toast.LENGTH_LONG).show();
						refreshConfigList();
					} catch (Exception e) {
						// TODO Auto-generated catch block
						Log.w("config", e);
						Toast.makeText(context, R.string.text_config_manage_result_failure, Toast.LENGTH_LONG).show();
					}
					dialog.dismiss();
				}
			});
			
			builder.setNegativeButton(R.string.text_button_cancel, new DialogInterface.OnClickListener() {
				
				public void onClick(DialogInterface dialog, int arg1) {
					// TODO Auto-generated method stub
					
					dialog.dismiss();
				}
			});
			
			addConfigDialog = builder.create();
		}
		return addConfigDialog;
	}
	
	public AlertDialog createDelConfirmDialog(final Context context){
		if(delConfirmDialog == null){
			AlertDialog.Builder builder = new AlertDialog.Builder(context);
			builder.setIcon(android.R.drawable.ic_dialog_alert);
			builder.setTitle(R.string.dialog_title_config_manage_delete);
			builder.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
				
				public void onClick(DialogInterface dialog, int buttonid) {
					// TODO Auto-generated method stub
					int count = 0;
					Iterator<Integer> iterator = adapter.getSelectedConfigs().iterator();
					while(iterator.hasNext()){
						try {
							configOpenHelper.deleteConfig(adapter.getConfigs().get(iterator.next()));
							count++;
						} catch (Exception e) {
							// TODO Auto-generated catch block
							Log.w("config", e);
						}
					}
					Toast.makeText(context, context.getText(R.string.toast_config_manage_delete_prefix).toString()
												+ count + 
												context.getText(R.string.toast_config_manage_delete_suffix).toString(), Toast.LENGTH_LONG).show();
					refreshConfigList();
				}
			});
			
			builder.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
				
				public void onClick(DialogInterface dialog, int arg1) {
					// TODO Auto-generated method stub
					
					dialog.dismiss();
				}
			});
			
			delConfirmDialog = builder.create();
		}
		return delConfirmDialog;
	}
	
	
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub
		getMenuInflater().inflate(R.menu.activity_config_manage, menu);
		menu.getItem(0).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
			
			@Override
			public boolean onMenuItemClick(MenuItem item) {
				// TODO Auto-generated method stub
				if(!adapter.isShowCheckBox()){
					adapter.setShowCheckBox(true);
					adapter.notifyDataSetChanged();
				}else{
					createDelConfirmDialog(ConfigManagerActivity.this).show();
				}
				return true;
			}
		});
		menu.getItem(1).setOnMenuItemClickListener(new OnMenuItemClickListener() {
			
			@Override
			public boolean onMenuItemClick(MenuItem item) {
				// TODO Auto-generated method stub
				refreshConfigList();
				return true;
			}
		});
		menu.getItem(2).setOnMenuItemClickListener(new OnMenuItemClickListener() {
			
			@Override
			public boolean onMenuItemClick(MenuItem item) {
				// TODO Auto-generated method stub
				for(int i=0;i<adapter.getConfigs().size();i++){
					adapter.getSelectedConfigs().add(i);
				}
				adapter.notifyDataSetChanged();
				return true;
			}
		});
		menu.getItem(3).setOnMenuItemClickListener(new OnMenuItemClickListener() {
			
			@Override
			public boolean onMenuItemClick(MenuItem item) {
				// TODO Auto-generated method stub
				for(int i=0;i<adapter.getConfigs().size();i++){
					if(adapter.getSelectedConfigs().contains(i)){
						adapter.getSelectedConfigs().remove(i);
					}else{
						adapter.getSelectedConfigs().add(i);
					}
				}
				adapter.notifyDataSetChanged();
				return true;
			}
		});
		menu.getItem(4).setOnMenuItemClickListener(new OnMenuItemClickListener() {
			
			@Override
			public boolean onMenuItemClick(MenuItem item) {
				// TODO Auto-generated method stub
				adapter.getSelectedConfigs().clear();
				adapter.setShowCheckBox(false);
				adapter.notifyDataSetChanged();
				return true;
			}
		});
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub
		if(adapter.isShowCheckBox()){
			menu.getItem(2).setVisible(true);
			menu.getItem(3).setVisible(true);
			menu.getItem(4).setVisible(true);
			menu.getItem(1).setVisible(false);
		}else{
			menu.getItem(2).setVisible(false);
			menu.getItem(3).setVisible(false);
			menu.getItem(4).setVisible(false);
			menu.getItem(1).setVisible(true);
		}
		return super.onPrepareOptionsMenu(menu);
	}



	class ConfigListAdapter extends BaseAdapter {
		
		private List<ConfigModel> configs;
		
		private Set<Integer> selectedConfigs = new HashSet<Integer>();
		
		private boolean showCheckBox;
		
		private Context context;
		
		public ConfigListAdapter(Context context, List<ConfigModel> configs){
			setContext(context);
			setConfigs(configs);
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return configs == null ? 0 : configs.size();
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return configs == null ? null : configs.get(position);
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		@Override
		public View getView(int position, View view, ViewGroup group) {
			// TODO Auto-generated method stub
			ConfigListItemHolder holder = null;
			if(view == null){
				LayoutInflater inflater = LayoutInflater.from(context);
				view = inflater.inflate(R.layout.list_item_config_manage, null);
				
				holder = new ConfigListItemHolder();
				holder.number = (TextView) view.findViewById(R.id.config_list_item_number);
				holder.content = (TextView) view.findViewById(R.id.config_list_item_content);
				holder.date = (TextView) view.findViewById(R.id.config_list_item_date);
				holder.checkBox = (CheckBox) view.findViewById(R.id.config_list_item_checkbox);
				holder.name = (TextView) view.findViewById(R.id.config_list_item_name);
				view.setTag(holder);
			}else{
				holder = (ConfigListItemHolder) view.getTag();
			}
			
			holder.number.setText(configs.get(position).getTarget_num());
			holder.content.setText(configs.get(position).getPost_content());
			holder.date.setText(DateTimeUtil.format(configs.get(position).getLast_edit()));
			holder.name.setText(configs.get(position).getConfig_name());
			if(showCheckBox){
				holder.checkBox.setVisibility(View.VISIBLE);
				if(selectedConfigs.contains(position)){
					holder.checkBox.setChecked(true);
				}else{
					holder.checkBox.setChecked(false);
				}
			}else{
				holder.checkBox.setVisibility(View.INVISIBLE);
			}
			
			return view;
		}

		public List<ConfigModel> getConfigs() {
			return configs;
		}

		public void setConfigs(List<ConfigModel> configs) {
			this.configs = configs;
		}

		public Set<Integer> getSelectedConfigs() {
			return selectedConfigs;
		}

		public void setSelectedConfigs(Set<Integer> selectedConfigs) {
			this.selectedConfigs = selectedConfigs;
		}

		public boolean isShowCheckBox() {
			return showCheckBox;
		}

		public void setShowCheckBox(boolean showCheckBox) {
			this.showCheckBox = showCheckBox;
		}

		public Context getContext() {
			return context;
		}

		public void setContext(Context context) {
			this.context = context;
		}

	}
	
	class ConfigListItemHolder {
		public TextView number;
		public TextView content;
		public CheckBox checkBox;
		public TextView date;
		public TextView name;
	}
}
